// #ifndef APP-PLUS
const jweixin = require('./jweixin.js');
// #endif
const tool = require('./tool.js');

var pay = {
	// H5支付
	doc: false,
	//插入html代码，初始化
	initHtml: function(doc) {
		this.doc = doc.$refs.initHtml.$el;
	},
	//插入html代码
	html: function(html) {
		var self = this;
		var div = document.createElement('div');
		div.innerHTML = html;
		this.doc.appendChild(div);
		var scripts = div.querySelectorAll('script');
		return Array.prototype.slice.apply(scripts).reduce((chain, script) => {
			return chain.then(() => self.runScript(script));
		}, Promise.resolve());
	},
	//执行script代码
	runScript: function(script) {
		return new Promise((reslove, rejected) => {
			const newScript = document.createElement('script');
			newScript.innerHTML = script.innerHTML;
			const src = script.getAttribute('src');
			if (src) newScript.setAttribute('src', src);
			// script 加载完成和错误处理
			newScript.onload = () => reslove();
			newScript.onerror = err => rejected();
			document.head.appendChild(newScript);
			document.head.removeChild(newScript);
			if (!src) {
				// 如果是 inline script 执行是同步的
				reslove();
			}
		})
	},
	
	
	
	// 支付
	payment:function(type, order_no, param) {
		console.log(type)
		console.log(param)
		// 回跳页面地址
		if (type == 'alipay_app' || type == 'wechat_app' || type == 'wechat_xcx') {
			this.appPayment(type, param, function(res) {
				uni.redirectTo({
					url:'/pages/payment/callback?order_no=' + order_no
				})
			}, function(err) {
				tool.msg('支付异常，请重下单重试');
				tool.payBack();
			});
			return;
		}
		if (type == 'alipay_wap' || type == 'wechat_wap') {
			this.html(param);
			uni.redirectTo({
				url:'/pages/payment/callback?order_no=' + order_no
			})
			return;
		}
		if (type == 'wechat_gzh') {
			this.wxJSApiPay(param, (res) => {
				tool.msg('支付成功','success');
				uni.redirectTo({
					url:'/pages/payment/callback?order_no=' + order_no
				})
			}, (err) => {
				tool.msg('支付异常，请重下单重试');
				tool.payBack();
			});
			return;
		}
		if (type == 'balance' && param.code == 1) {
			uni.redirectTo({
				url:'/pages/payment/callback?order_no=' + order_no
			})
			return;
		}
	},
	
	// app支付
	appPayment: function(type, param, callback, errorCallback) {
		let paymentType;
		switch (type) {
			// 微信APP
			case 'wechat_app':
				paymentType = 'wxpay'
				break;
				// 微信小程序
			case 'wechat_xcx':
				paymentType = 'wxpay'
				break;
				// 阿里APP支付
			case 'alipay_app':
				paymentType = 'alipay'
				break;
		}
		uni.requestPayment({
			provider: paymentType,
			orderInfo: param,
			success: function(res) {
				if (callback) {
					callback(res);
				}
			},
			fail: function(err) {
				console.log('fail:' + JSON.stringify(err));
				if (errorCallback) {
					errorCallback(err)
				}
			}
		});
	},

	// 微信公众号支付
	wxJSApiPay: function(data, callback, errorCallback) {
		jweixin.config({
			debug: false, // 开启调试模式
			appId: data.appId, // 必填，公众号的唯一标识
			timestamp: data.timeStamp, // 必填，生成签名的时间戳
			nonceStr: data.nonceStr, // 必填，生成签名的随机串
			signature: data.paySign, // 必填，签名，见附录1
			jsApiList: ['checkJsApi', 'startRecord', 'stopRecord', 'translateVoice', 'scanQRCode',
				'openCard'
			] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
		});

		jweixin.ready(function() {
			jweixin.checkJsApi({
				jsApiList: ['checkJsApi', 'startRecord', 'stopRecord', 'translateVoice',
					'scanQRCode', 'openCard'
				],
				success: (res) => {},
				fail: function(res) {
					tool.msg('支付呼起失败');
				}
			});
			jweixin.chooseWXPay({
				timestamp: data.timeStamp,  
				nonceStr: data.nonceStr,  
				package: data.package,  
				signType: data.signType,  
				paySign: data.paySign, 
				success: (res) => {
					tool.msg(res);
					// 前端判断返回方式，微信团队郑重提示：不保证绝对可靠，切记！
					if (res.errMsg == 'chooseWXPay:ok' && callback) {
						callback(res);
					}else {
						tool.msg('支付失败，请重试');
					}
					
				},
				cancel: (r) => {
					tool.msg('支付已取消');
				},
				fail: (err) => {
					if (errorCallback) {
						errorCallback(err)
					}

				}
			});
		});
		// config信息验证失败会执行error函数，
		jweixin.error(function(res) {
			console.log('jweixin.error失败：', res)
		});


	}

}

module.exports = pay;
